;layui.define(["jquery",'form'], function (exports) {
    var layer = layui.layer, $ = layui.jquery,form=layui.form;
    var IsDebug = true;

    var  padZero=function(str,length){
        return new Array(length - str.length + 1).join("0") + str;
    };
    //ajax全局设置
    $.ajaxSetup({
        //contentType:"application/x-www-form-urlencoded;charset=utf-8",
        //发送请求前触发
        beforeSend: function (xhr) {
            var resId = common.getResId();
            if(resId) {
                //可以设置自定义标头
                xhr.setRequestHeader('resId', resId);
            }
        },
        complete:function(XMLHttpRequest,textStatus){
        },
        statusCode: {
            401: function() {
                layer.alert('你还未登录或登录过期,请重新登录');
                window.top.location.href ="/login";  //重新登录
            },
            403: function() {
                layer.alert('对不起，你没有访问该资源的权限');
            },
            500: function() {
                layer.alert('调用服务出错 500');
            }
        }
    });

    //---------------------------------------------------
    // 日期格式化
    // 格式 YYYY/yyyy/YY/yy 表示年份
    // MM/M 月份
    // W/w 星期
    // dd/DD/d/D 日期
    // hh/HH/h/H 时间
    // mm/m 分钟
    // ss/SS/s/S 秒
    // fff毫秒
    //---------------------------------------------------
    Date.prototype.Format = function (formatStr) {
        var str = formatStr;
        var Week = ['日', '一', '二', '三', '四', '五', '六'];

        str = str.replace(/yyyy|YYYY/, this.getFullYear());
        str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
        //月 0～11
        str = str.replace(/MM/, this.getMonth() + 1 > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
        str = str.replace(/M/g, this.getMonth() + 1);

        str = str.replace(/w|W/g, Week[this.getDay()]);

        str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
        str = str.replace(/d|D/g, this.getDate());

        str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
        str = str.replace(/h|H/g, this.getHours());
        str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
        str = str.replace(/m/g, this.getMinutes());

        str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
        str = str.replace(/s|S/g, this.getSeconds());

        str = str.replace(/fff/g, padZero(this.getMilliseconds().toString() ,3));
        return str;
    }
    var common ={
        getUrlParam:function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]); return null; //返回参数值
        },
        getUrlDecodeParam:function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = decodeURIComponent(window.location.search).substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]); return null; //返回参数值
        },
        getParentUrlParam:function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.parent.location.search.substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]); return null; //返回参数值
        },
        getParentResId:function() {
            return this.getParentUrlParam("resId");
        },
        getResId:function(){
            var resId = this.getUrlParam("resId");
            if(!resId){
                //取父页面url
                resId=this.getParentUrlParam("resId");
            }
            return resId;
        },
         //替换所有的回车换行  
        formatString4Html:function (content)  
        {  
            var string = content;  
            try{  
                string=string.replace(/\r\n/g,"<br>")  
                string=string.replace(/\n/g,"<br>");  
            }catch(e) {  
            }  
            return string;  
        } ,
        getGridheight:function() {
            if (!$.support.style)
                return $(window).height() - 80;
            else
                return $(window).height() - 10;
        },
        getGridwidth:function() {
            //return $(window).width() * 0.99;
            var width = document.body.clientWidth;
            return (width - 100);
        } ,
        getWidth:function() {
            var winWidth = 0;
            if (window.innerWidth)
                winWidth = window.innerWidth;
            else if ((document.body) && (document.body.clientWidth))
                winWidth = document.body.clientWidth;
            if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
                winWidth = document.documentElement.clientWidth;
            }
            return winWidth;
        },
        getHeight:function() {
            var winHeight = 0;
            if (window.innerHeight)
                winHeight = window.innerHeight;
            else if ((document.body) && (document.body.clientHeight))
                winHeight = document.body.clientHeight;
            if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
                winHeight = document.documentElement.clientHeight;
            }
            return winHeight;
        },
        padZero:function(str,length){
            return new Array(length - str.length + 1).join("0") + str;
        },
        formatValue:function(value){
        if(value=="0") return value;
        if(!value) return ""
        else if(value=="null") return "";
        else if(value=="NULL") return "";
        else return value;
    },
     formatLongText:function(str,len){
        if(str.length > len ) return str.substr(0,len) +"...";
        else return str;
    },
     toDecimal2:function(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return 0;
        }
        return f.toFixed(2);
    },
     toInt:function(x){
        var i = parseInt(x);
        if (isNaN(i)) {
            return 0;
        }
        return i;
    },
      checkMobile:function(str) {
        var  re = /^1\d{10}$/;
        if(re.test(str)) {
            return true;
        } else {
            return false;
        }
    },

//日志处理
//ie9以下低版本不支持console
     consoleLog:function(log){
        if(window.console){
            console.log((new Date()).Format("yyyy-MM-dd HH:mm:ss")+" : "+log);
        }
    },
     consoleDebug:function(log){
        if(IsDebug){
            this.consoleLog(log);
        }
    },
        //下拉框初始化
        initSelectData:function(obj,url,calback) {
        $.ajax({
            type: 'get',
            url: url,
            dataType: 'json',
            success: function(rtn) {
                if (rtn && rtn.code == 0) {
                    var optionHtml = '';
                    var data = rtn.data;
                    for (var i = 0; i < data.length; i++) {
                        optionHtml += '<option value="' + data[i].code + '">' + data[i].name + '</option>';
                    }
                    $(obj).empty().append(optionHtml);
                }
            },
            error: function() {
                console.error("init select error");
            }
        })
            .always(function () {
                form.render('select');
                if(calback) calback();
            });
    },
        //下拉框初始化
        initCommSelectData:function(obj,url,bl,calback) {
            $.ajax({
                type: 'get',
                url: url,
                dataType: 'json',
                success: function(rtn) {
                    if (rtn && rtn.code == 0) {
                        var optionHtml = '';
                        var data = rtn.data;
                        if(bl){
                            optionHtml += '<option value="">请选择</option>';
                        }
                        for (var i = 0; i < data.length; i++) {
                            optionHtml += '<option value="' + data[i].dictKey + '">' + data[i].dictValue + '</option>';
                        }
                        $(obj).empty().append(optionHtml);
                    }
                },
                error: function() {
                    console.error("init select error");
                }
            })
                .always(function () {
                    form.render('select');
                    if(calback) calback();
                });
        },
    //提示消息
     showError:function(content,calback) {
        layer.open({
            title:'处理出错'
            ,icon: 2
            ,content: content,
            end:function(){
                if(calback) calback();
            }
        });
    },
     showInfo:function(content,calback) {
        layer.open({
            title:'消息'
            ,icon: 1
            ,content: content,
            end:function(){
                if(calback) calback();
            }
        });
    },
     showMsg:function(msg,time){
        layer.msg(msg, {
            icon: 1,
            time: time
        });
    },
    /*弹出层*/
    /*
        参数解释：
        title	标题
        url		请求的url
        id		需要操作的数据id
        w		弹出层宽度（缺省调默认值）
        h		弹出层高度（缺省调默认值）
    */
     layer_show:function(title,url,w,h) {
         if (title == null || title == '') {
             title = false;
         }
         ;
         if (url == null || url == '') {
             url = "404.html";
         }
         ;
         if (w == null || w == '' || w == undefined) {
             //w=800;
             w = ($(window).width() - 50) + "px";
         } else if (w.indexOf("%") < 0) {
             w = w + 'px';
         }
         ;
         if (h == null || h == '' || h == undefined) {
             h = ($(window).height() - 50) + "px";
         } else if (w.indexOf("%") < 0) {
             h = h + 'px';
         }
         var index = layer.open({
             type: 2,
             area: [w, h],
             fix: false, //不固定
             maxmin: true,
             //shadeClose: true,
             shade: 0.4,
             title: title,
             content: url
         });
     },
    /*关闭弹出框口*/
     layer_close:function(){
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
    },
        ptabAdd:function(id,title,src,icon){
            window.parent.layui.tab.tabAdd({
                id:id,
                title:title,
                icon:icon,
                name:title,
                url:src
            });
        },
        dateAddDay:function(n) {
        if(!n) n=1;
        var myDate = new Date();
        var a = myDate.valueOf()
        a = a + n * 24 * 60 * 60 * 1000
        return  new Date(a);
    },
        dataFormat:function(date,formatStr){
         if(!date) return '';
         if(!formatStr) formatStr = "YYYY-MM-DD HH:mm:SS";
         return (new Date(date)).Format(formatStr);
        },
         dateAddMonth:function(n) {
            if(!n) n=1;
            var myDate = new Date();
            myDate.setMonth(myDate.getMonth() + n);
            return myDate;
        },
         getMonthLastDay:function(curDate){
            if(!curDate) curDate = new Date();
            var newdate = new Date(curDate.getFullYear(),curDate.getMonth(),1); //本月第一天
            newdate.setMonth(newdate.getMonth() + 1); //下一月
            var oneDay=1000*60*60*24;
            newdate = new Date(newdate-oneDay);
            return newdate;
        },
        getMonthStart:function(){
            return (new Date()).Format("YYYY-MM-01 00:00:00");
        },
        getMonthEnd:function(){
            return this.getMonthLastDay().Format("YYYY-MM-DD 23:59:59");
        },
        getTodayStart:function(){
            return (new Date()).Format("YYYY-MM-DD 00:00:00");
        },
        getTodayEnd:function(){
            return (new Date()).Format("YYYY-MM-DD 23:59:59");
        },
        getTodayNow:function(){
            return (new Date()).Format("YYYY-MM-DD HH:mm:SS");
        },
        getToday:function(){
            return (new Date()).Format("YYYY-MM-DD");
        },
         formatTimestamp:function(value) {
            if(!value) return "";
            else
                return (new Date(value)).Format("YYYY-MM-DD HH:mm:SS");
        },
        /**
         *
         * @param num
         * @param precision
         * @param separator
         * @returns {*}
         *=======================================================
         *     formatNumber(10000)="10,000"
         *     formatNumber(10000, 2)="10,000.00"
         *     formatNumber(10000.123456, 2)="10,000.12"
         *     formatNumber(10000.123456, 2, ' ')="10 000.12"
         *     formatNumber(.123456, 2, ' ')="0.12"
         *     formatNumber(56., 2, ' ')="56.00"
         *     formatNumber(56., 0, ' ')="56"
         *     formatNumber('56.')="56"
         *     formatNumber('56.a')=NaN
         *=======================================================
         */
         formatNumber:function(num, precision, separator) {
            var parts;
            // 判断是否为数字
            if (!isNaN(parseFloat(num)) && isFinite(num)) {
                // 把类似 .5, 5. 之类的数据转化成0.5, 5, 为数据精度处理做准, 至于为什么
                // 不在判断中直接写 if (!isNaN(num = parseFloat(num)) && isFinite(num))
                // 是因为parseFloat有一个奇怪的精度问题, 比如 parseFloat(12312312.1234567119)
                // 的值变成了 12312312.123456713
                num = Number(num);
                // 处理小数点位数
                num = (typeof precision !== 'undefined' ? num.toFixed(precision) : num).toString();
                // 分离数字的小数部分和整数部分
                parts = num.split('.');
                // 整数部分加[separator]分隔, 借用一个著名的正则表达式
                parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + (separator || ','));

                return parts.join('.');
            }
            return NaN;
        },
        startWith:function(str,char){
            if(char==null||char==""||str.length==0||char.length>str.length)
                return false;
            if(str.substr(0,char.length)==char)
                return true;
            else
                return false;
        },
        endWith:function(str,char){
            if(char==null||char==""||str.length==0||char.length>str.length)
                return false;
            if(str.substring(str.length-char.length)==char)
                return true;
            else
                return false;
        },
        nvl: function (val, defaultVal) {
            if (val && val != null && val != 'null') {
                return val;
            }
            else {
                return defaultVal;
            }
        },
        checkDate :function(date){
            return (new Date(date).getDate()==date.substring(date.length-2));
        },
    }
    exports('common', common);
});